import base64
import pickle


from django_redis import get_redis_connection


def merge_carts(request,response):
    cookie_bytes = request.COOKIES.get('carts')
    if not cookie_bytes:
        return
    cookie_dict = pickle.loads(base64.b64decode(cookie_bytes.encode()))
    redis_conn = get_redis_connection('carts')
    # sku_dict = redis_conn.hgetall('carts%s' %request.user.id)
    # sku_selected = redis_conn.smembers('selected%s' %request.user.id)
    for sku_id,values in cookie_dict.items():
        redis_conn.hset('carts%s'%request.user.id,sku_id,values['count'])
        if values['selected']:
            redis_conn.sadd('selected%s'%request.user.id,sku_id)
        else:
            redis_conn.srem('selected%s'%request.user.id,sku_id)
    response.delete_cookie('carts')

